var remove = require('orderd-array-remove')

//  Efficiently remove an element from an unordered array without doing a splice
// unordered-array-remove

// Removed an element from array by keeping order of elements inside array
// npm install --save orderd-array-remove

var list = ['a', 'b', 'c', 'd', 'e']
console.log( remove(list, 2) ) // remove 'c'
console.log(list) // returns ['a', 'b', 'e', 'd'] (no 'c')

console.log( remove(list, 1) ) 
console.log(list) 
console.log('--------------------------')
var arr = [1, 2, 3, 4, 5]
var ret = remove(arr, 2)
console.log(arr, ret , arr === ret);

console.log('--------------------------')
 
var arr = [1, 2, 3, 4, 5]
var ret = orderedArrayRemoveV2(arr, 2)
console.log(arr, ret , arr === ret);



function orderedArrayRemoveV2(arr, val) {
  var location = arr.indexOf(val)
  if(location !== -1) { 
    arr.splice(location, 1)
  }
  return arr
}

/**
 * 删除元素，保留索引
 * @param  {[type]} arr [description]
 * @param  {[type]} val [description]
 * @return {[type]}     [description]
 */
function  orderedArrayRemove(arr, val) {
  var findIndex = -1
  for (var i = 0; i < arr.length; i++) {
    if(arr[i] === val) {
      findIndex = i
      break
    }
  }

  if(findIndex === -1) {
    return arr
  }

  for (var i = findIndex; i < arr.length-1; i++) {
    arr[i] = arr[i+1]
  }
  // 删除一个元素 长度减去1
  arr.length --

  return arr
}



/**
 * 保持顺序的删除数组的某个索引的元素 (按照索引进行删除)
 * @param arr
 * @param idx
 */
function  orderedArrayRemoveV1(arr, idx) {
  var len = arr.length
  if(idx <0 || idx>=len) return

  var delOne = arr[idx]
  for(var i = idx; i < len-1 ; i++) {
    arr[i] = arr[i+1]
  }
   // 删除一个元素 长度减去1
  arr.length --

  return delOne
}

